#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/8/16 16:32
# @Author  : 李中华
# @Email   : 1260429766@qq.com
# @File    : getCookies.py
from selenium import webdriver
import time
from common.logger import Log
from common.codecTools import urlCodecTool
from common.writeConfig import WriteConfig
from common.readConfig import ReadConfig

logger = Log()


class MyDriver:

    def __init__(self):
        option = webdriver.ChromeOptions()
        option.add_argument('--ignore-certificate-errors')
        self.driver = webdriver.Chrome(options=option)
        logur = ReadConfig().getConfValue('mskjWebPlateform', 'logurl')
        self.logurl = logur + "/#/login?redirect=%2Fdashboard"

    def logManual(self):
        '''
        当其他地方登录后，cookies变化，此时需要手动登录，获取cookies，并写入到配置文件中，
        如果其他地方没有登录，cookies没有变，先清除cookies，再从配置文件中获取cookies，自动登录
        :return cook，为登录后的cookies:
        '''
        logger.info(self.logurl)
        self.driver.get(self.logurl)
        print('登录前cookie：', self.driver.get_cookies())
        self.driver.implicitly_wait(5)
        self.driver.find_element_by_xpath("//input[@type='text']").click()
        self.driver.find_element_by_xpath("//input[@type='text']").clear()
        self.driver.find_element_by_xpath("//input[@type='text']").send_keys("admin")
        self.driver.find_element_by_xpath("//input[@type='password']").clear()
        self.driver.find_element_by_xpath("//input[@type='password']").send_keys("mskj0417")
        self.driver.find_element_by_xpath("/html/body/div/div/form/div/div[3]/div/div[1]/input").clear()
        code = self.driver.find_element_by_xpath('/html/body/div/div/form/div/div[3]/div/div[1]/input')

        print('\n请输入验证码\n')
        codeId = input()
        code.send_keys(codeId)
        self.driver.find_element_by_xpath('/html/body/div/div/form/div/div[4]/div/button').click()
        time.sleep(5)
        result = self.driver.title
        print(result)
        cook = self.driver.get_cookies()  # 此时获取到的cook是url编码之后的cookies，不能用，需要url解码
        # print('登录后cookie：', cook)
        cookies = []
        c = {}
        for cookie in cook:
            for key in cookie.keys():
                if isinstance(cookie[key], str):
                    if key == 'name' or key == 'value':  # url解码cook，只需要name和value，其余不需要，登录是用此cookies会自动把其余不全
                        c[key] = urlCodecTool(cookie[key]).urlDecode

            cookies.append(c)
            c = {}
        logger.info('通过手动登录，解析之后的cookies为：' + str(cookies))
        # #cookies写入到配置文件中
        WriteConfig().setConfig('admin登录入口', 'cookies', str(cookies))
        return cookies

    def loginAuto(self):
        """从配置文件中获取cookies，自动登录"""
        cookies = eval(ReadConfig().getConfValue('admin登录入口', 'cookies'))
        self.driver.delete_all_cookies()
        self.driver.get(self.logurl)
        for cookie in cookies:
            self.driver.add_cookie(cookie)
        print("使用cookies登录后的cookie：", self.driver.get_cookies())
        self.driver.refresh()
        time.sleep(5)
        return self.driver

    def login(self):

        cookies = self.logManual()
        self.driver.delete_all_cookies()
        for cookie in cookies:
            self.driver.add_cookie(cookie)
        self.driver.get(self.logurl)
        print("骚操作后的cookie：", self.driver.get_cookies())
        self.driver.refresh()
        time.sleep(5)
        return self.driver


if __name__ == '__main__':
    # print(MyDriver().logManual())
    # MyDriver().loginAuto()
    # MyDriver().login()
    MyDriver().loginAuto()
